package top.wenzz.manage.system.manage.service;

import lombok.Builder;
import lombok.Data;
import org.springframework.stereotype.Service;
import top.wenzz.commons.service.BasicService;
import top.wenzz.manage.system.manage.dao.OvertimeRecordDao;
import top.wenzz.manage.system.manage.entity.OvertimeRecord;
import top.wenzz.manage.system.manage.entity.SysPermission;

import java.sql.Date;
import java.util.*;

/**
 * 加班记录service
 * Created by 钟廷员 on 2017/8/8.
 */
@Service
public class OvertimeStatisticsService extends BasicService<OvertimeRecord, OvertimeRecordDao> {

    public Object statistics(OvertimeRecord entity) {
        Map<Date, Set<String>> map = new HashMap<>();
        super.find(entity).forEach(e -> {
            if(!map.containsKey(e.getDate()))
                map.put(e.getDate(), new LinkedHashSet<>());
            map.get(e.getDate()).add(e.getUser().getName());
        });
        List<Statistics> list = new ArrayList<>();
        map.forEach((key, value) -> list.add(Statistics.builder().date(key).names(set2Str(value)).num(value.size()).build()));
        list.sort(Comparator.comparing(Statistics::getDate));
        return toExtjsQuery(list, 0, null);
    }

    @Builder
    @Data
    private static class Statistics {
        Date date;
        String names;
        int num;
    }

    private static String set2Str(Set<String> set) {
        Iterator<String> it = set.iterator();
        if (! it.hasNext())
            return "【】";

        StringBuilder sb = new StringBuilder();
        sb.append('【');
        for (;;) {
            String e = it.next();
            sb.append(e);
            if (! it.hasNext())
                return sb.append('】').toString();
            sb.append(',');
        }
    }
}
